package edu.kit.los.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.evdb.javaapi.APIConfiguration;
import com.evdb.javaapi.EVDBAPIException;
import com.evdb.javaapi.EVDBRuntimeException;
import com.evdb.javaapi.data.request.EventSearchRequest;
import com.evdb.javaapi.operations.EventOperations;

import edu.kit.los.event.StandardEvent;

/**
 * Servlet, das Anfragen an Eventful verwaltet.
 * @author Felix Kiechle, Benedikt Fuss  AIFB@BKIT
 * 
 */
public class EventFulLookup extends HttpServlet{

	/**
	 * Für Serialisierung
	 */
	private static final long serialVersionUID = 4159405911499481591L;
	/**
	 * Key für die API
	 */
	private static final String key = "xKxMczSsF8MDk5TF";
	/**
	 * Liste zum speichern der Events
	 */
	List<com.evdb.javaapi.data.Event> eventfulListe = null; 
	
	
	/**
	 * Führt mit Hilfe der Eventful-Java Api einen Lookups bei Eventful durch
	 * und schreibt das Ergebnis als RDF/XML auf den Outputstream.
	 * 
	 * @param HttpservletRequest request      
	 * @param HttpServletResponse response
	 * @throws ServletException
	 * @throws IOExceptionn
	 * 	 
	*/
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//Parameter anfragen
		Map<String, String> param = Servlet.parameters(request);
		String query = param.get("query");
		int limit = Integer.parseInt(param.get("limit"));
		//Outputstream
		OutputStream out = response.getOutputStream();
		edu.kit.los.Model model = new edu.kit.los.Model();
		response.setContentType(Servlet.contentType_RDF);
		//Bei der API registrieren
		APIConfiguration.setEvdbUser("Kiechlus");
		APIConfiguration.setEvdbPassword("eventsearch");
		APIConfiguration.setApiKey(key);
		
		//Request starten
		EventSearchRequest req = new EventSearchRequest();
		req.setPageSize(limit);
		req.setKeywords("title:"+query);
		EventOperations op = new EventOperations();
		com.evdb.javaapi.data.SearchResult result = null;
		try {
			result = op.search(req);
			eventfulListe = result.getEvents();
			//Liste der Events in StandardEvents umwandeln und in Stream schreiben 
			for(com.evdb.javaapi.data.Event event : eventfulListe){
				model.addEvent(new StandardEvent(event));
			}
		} 
		catch (EVDBAPIException e) {
			e.printStackTrace();
		} 
		catch (EVDBRuntimeException e) {	
			e.printStackTrace();
		}
		model.writeRDF(out);
	}
}
